package com.ocm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ocm.controller.validator.StorageValidator;
import com.ocm.core.dto.StorageDto;
import com.ocm.core.mapping.DTOConfiguration;
import com.ocm.core.mapping.IDMapping;
import com.ocm.core.service.StorageService;

@Controller
public class StorageController {

   public static final String ADD_PAGE = "storage/add";
   public static final String VIEW_PAGE = "storage/view";
   public static final String COMPLETE_PAGE = "storage/complete";
   public static final String ITEMS_TREE_PAGE = "storage/itemsTree";
   public static final String STATUS_PAGE = "storage/status";

   private StorageService storageService;
   private StorageValidator storageValidator;

   @Autowired
   public StorageController(
      @Qualifier("storageService") StorageService storageService,
      @Qualifier("storageValidator") StorageValidator storageValidator) {
      this.storageService = storageService;
      this.storageValidator = storageValidator;
   }

   @RequestMapping(value = "/storage/add", method = RequestMethod.GET)
   public String viewAddForm(ModelMap model) {
      return ADD_PAGE;
   }

   @RequestMapping(value = "/storage/complete", method = RequestMethod.GET)
   public String viewCompleteForm(ModelMap model) {
      return COMPLETE_PAGE;
   }

   @RequestMapping(value = "/storage/{storageId}/view", method = RequestMethod.GET)
   public String viewViewPage(@PathVariable("storageId")long storageId, ModelMap model) {
      model.addAttribute("storageId", storageId);
      return VIEW_PAGE;
   }

   @RequestMapping(value = "/storage/create", method = RequestMethod.POST)
   public String createStorage(@ModelAttribute("storage") StorageDto storageDto, BindingResult result, ModelMap model) {
      storageValidator.validate(storageDto, result);
      if (!result.hasErrors()){
         this.storageService.create(storageDto);
         String storageName = storageDto.getName();
         StorageDto storageSaved = this.storageService.getStorage(storageName, DTOConfiguration.instance(IDMapping.STORAGE_LIMIT));
         model.addAttribute("storageSaved", storageSaved);
      }
      return STATUS_PAGE;
   }
}
